/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* left;
    Node* right;
    Node* next;

    Node() : val(0), left(NULL), right(NULL), next(NULL) {}

    Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}

    Node(int _val, Node* _left, Node* _right, Node* _next)
        : val(_val), left(_left), right(_right), next(_next) {}
};
*/

class Solution {
public:
    Node* connect(Node* root) {
        Node* res = root;
        if(!root)
            return res;
        
        queue<Node*> cnt_layer;
        cnt_layer.push(root);

        while(!cnt_layer.empty())
        {
            int size = cnt_layer.size();
            Node* pre = cnt_layer.front();
            pre->next = NULL;
            for(int i = 0; i < size; i++)
            {
                Node* node = cnt_layer.front();
                pre->next = node;
                node->next = NULL;
                pre = node;
                if(node->left)
                    cnt_layer.push(node->left);
                if(node->right)
                    cnt_layer.push(node->right);
                cnt_layer.pop();
            }
        }

        return res;
    }
};

/*
// Definition for a Node.
class Node {
public:
    int val;
    Node* left;
    Node* right;
    Node* next;

    Node() : val(0), left(NULL), right(NULL), next(NULL) {}

    Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}

    Node(int _val, Node* _left, Node* _right, Node* _next)
        : val(_val), left(_left), right(_right), next(_next) {}
};
*/

class Solution {
public:
    Node* connect(Node* root) {
        if(!root)
            return root;
        Node* left = root;
        while(left->left)
        {
            Node* head = left;
            left = head->left;
            while(head)
            {
                if(head->left)
                    head->left->next = head->right;
                if(head->next)
                    head->right->next = head->next->left;
                head = head->next;
            }
        }

        return root;
    }
};